<template>
  <el-dialog title="新增问题" :visible.sync="visible" :before-close="close">
    <el-form ref="form" :model="form" label-width="85px" :rules="rules">
      <el-form-item label="问题描述" prop="message">
        <el-input v-model="form.message" type="textarea" />
      </el-form-item>
      <el-form-item label="参数" prop="params">
        <el-input v-model="form.params" type="textarea" :rows="4" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="sure">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { add_question } from '../api'
import { get } from '@/utils/storage'

export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data: function() {
    const validate_params = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入请求参数'))
      } else {
        try {
          JSON.parse(value)
          callback()
        } catch (error) {
          callback(new Error('请确保参数为JSON格式'))
        }
      }
    }
    return {
      doc_id: '',
      form: {
        message: '',
        params: ''
      },
      rules: {
        params: [{ required: true, trigger: 'blur', validator: validate_params }],
        message: [{ required: true, message: '请输入问题描述', trigger: 'blur' }]
      }
    }
  },
  methods: {
    show(doc_id) {
      this.doc_id = doc_id
    },
    close() {
      this.$emit('dialog-close')
    },
    sure() {
      // 确定逻辑
      this.$refs.form.validate(async(valid) => {
        if (valid) {
          const editor = get('user_code')
          const params = JSON.parse(this.form.params)
          const res = await add_question(this.doc_id, this.form.message, editor, params)
          if (res.code === -1) {
            this.$message({
              message: '请检查参数',
              type: 'error',
              duration: 2 * 1000
            })
          }
          this.$message({
            message: '创建问题成功',
            type: 'success',
            duration: 2 * 1000
          })
          this.$emit('dialog-sure')
        }
      })
    }
  }
}
</script>

<style lang='scss' scoped>

</style>
